<template>
  <view class="main">
    <Tab
      v-if="!isLoading && dataInfo"
      :tabs="tabs"
      :current="currentTab"
      @change="onChangeTab"
    ></Tab>
    <!-- 设备档案 -->
    <swiper
      :current="currentTab"
      class="swiper"
      @change="onChangeSwiper"
      v-if="!isLoading && dataInfo"
    >
      <swiper-item>
        <view class="equipment-infos">
          <view class="equipment-info">
            <view class="title">基础信息</view>
            <view class="info">
              <view class="content"
                ><text class="text"
                  >设备名称：
                  <!-- {{ dataInfo.device_name }} -->
                  {{ dataInfo.alias_name || dataInfo.device_name }}
                </text></view
              >
              <view class="content">
                <view class="text"
                  >设备ID：{{ dataInfo.thingId || "暂无" }}

                  <image
                    :src="qrcodeSacnURL"
                    mode="widthFix"
                    class="qrcodeURL"
                    @click="onClickShowQrcode"
                  />
                </view>
              </view>
              <view class="content">
                <text class="text"> 设备编号：{{ dataInfo.no || "暂无" }}</text>
              </view>
              <view class="content">
                <text class="text">
                  设备型号：{{ dataInfo.model_no || "暂无" }}</text
                >
              </view>
              <view class="content">
                <text class="text"
                  >出产日期：{{ dataInfo.product_time || "暂无" }}</text
                >
              </view>
              <!-- 暂无 -->
              <view class="content">
                <!-- @click="openService" -->
                <view class="text"
                  >所属厂商：
                  <!-- service-provider -->
                  {{ dataInfo.manufacturer || "暂无" }}
                  <!-- <text class="">{{
                    dataInfo.servicer ? dataInfo.servicer.name : ""
                  }}</text> -->
                </view></view
              >

              <view class="content"
                ><text class="text"
                  >维保日期：{{ dataInfo.service_end_time || "暂无" }}</text
                ></view
              >
            </view>
          </view>
          <view class="equipment-info">
            <view class="title">客户信息</view>
            <view class="info">
              <view class="content"
                ><text class="text"
                  >企业名称：{{
                    dataInfo.company ? dataInfo.company.name : ""
                  }}</text
                ></view
              >
              <view class="content">
                <text class="text"
                  >联系人：{{
                    dataInfo.keyContact && showContact
                      ? dataInfo.keyContact || ""
                      : "****"
                  }}</text
                >
                <image
                  class="contact-right-icon"
                  :src="imgBaseUrlV1 + 'eye.png'"
                  mode="widthFix"
                  v-if="!showContact"
                  @click="showContact = true"
                ></image>
                <image
                  class="contact-right-icon"
                  :src="imgBaseUrlV1 + 'eye_h.png'"
                  mode="widthFix"
                  v-else
                  @click="showContact = false"
                ></image>
              </view>
            </view>
          </view>
          <view class="equipment-info">
            <view class="title"
              >设备维护人员
              <text class="operation" @click="onEdidUser"> 编辑 </text>
            </view>
            <view class="info" v-if="dataInfo.user">
              <view
                class="content"
                v-for="(user, uIndex) in dataInfo.user"
                :key="uIndex"
              >
                <view class="text"
                  >维护人员：{{ user.name }}/{{ user.mobile }}</view
                >
              </view>
            </view>
          </view>
          <view class="equipment-info">
            <view class="title"
              >附件信息
              <text class="operation" @click="onUpload"> 上传 </text>
            </view>
            <view class="upload" v-show="dataInfo.attachment">
              <Upload
                :imgList="dataInfo.attachment"
                :uploadWidth="146"
                :uploadHeight="146"
                :custom="true"
                :showDelete="false"
                :longDelete="true"
                @deleteImg="onDeleteImg"
                @uploadSuccess="uploadSuccess"
              ></Upload>
            </view>
          </view>
        </view>
      </swiper-item>

      <swiper-item>
        <!-- 服务申请记录 -->
        <view>
          <view class="service-records" v-if="serviceOrderRecords.length">
            <view
              class="item"
              v-for="(service, index) in serviceOrderRecords"
              :key="service.id"
              @click="openServiceRecordDetail(service, index)"
            >
              <service-log
                :status="service.status"
                :updateTime="service.update_time"
                :createTime="service.create_time"
                :title="service.service_type"
                :no="service.service_no"
              >
              </service-log>
            </view>
          </view>
          <view v-else class="maintenance-view">
            <view class="maintenance-record-group">
              <view class="info">
                <text>暂无服务记录！</text>
              </view>
            </view>
          </view>
        </view>
      </swiper-item>

      <swiper-item>
        <!-- 维护记录 -->
        <view>
          <view class="maintenance-view" v-if="maintenanceRecords.length !== 0">
            <view
              class="maintenance-record-group"
              v-for="record in maintenanceRecords"
              :key="record.id"
            >
              <view class="info" @click="toggleFold(record)">
                <view class="bd">
                  <text>检查日期：{{ record.check_date || "" }}</text>
                </view>
                <view class="ft">
                  <view
                    :class="[
                      record.hasException ? 'status-error' : 'status-normal',
                    ]"
                  >
                    <view class="circle"></view>
                    <text>{{ record.hasException ? "异常" : "正常" }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view v-else class="maintenance-view">
            <view class="maintenance-record-group">
              <view class="info">
                <view class="bd">
                  <text class="check-date">暂无维护记录！</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>

    <uni-popup ref="popup" type="bottom">
      <dictType
        :list="userList"
        title="选择维护人员"
        @checked="onCheckedUser"
        @confirm="onConfirmUser"
        @cancel="onCancelUser"
      ></dictType>
    </uni-popup>

    <popup-loading ref="popupLoading"></popup-loading>

    <Message ref="message"></Message>
  </view>
</template>

<script>
import detailModule from "@/common/mixins/detail-module";
/* 设备数字档案 */
import {
  getEquipmentTypeOptions,
  putEquipmentEquipmentType,
  deleteEquipmentEquipmentType,
} from "@/common/api/equipment-type.js";
/* 服务申请记录 */
import { getServiceOrderRecords2 } from "@/common/api/service-order-record.js";
/* 维护记录 */
import { getMaintenanceRecords2 } from "@/common/api/maintenance-record.js";
import Upload from "@/components/public/upload";
import dictType from "@/components/public/dictType";
import uniPopup from "@/components/uni-popup/uni-popup";
import popupLoading from "@/components/public/loading/popup";
import { mapState } from "vuex";
import { delayFunc } from "@/common/util";
import serviceLog from "@/components/public/item/serviceLog";
import Tab from "@/components/public/tabs/service";
import Router from "@/common/js/router";
import {
  getEquipment,
  editMaintrinUser,
  editAttachFile,
} from "@/common/api/equipment.js";

import {
  imgBaseUrl,
  uploadUrl,
  imgBaseUrlV0,
  imgBaseUrlV1,
  imgBaseUrlV2,
} from "@/common/config/index";
import { getCompanyUserList } from "@/common/api/user";
export default {
  mixins: [detailModule],
  components: {
    Upload,
    dictType,
    uniPopup,
    popupLoading,
    serviceLog,
    Tab,
  },
  computed: {
    ...mapState("User", ["token"]),
  },
  data() {
    return {
      imgBaseUrl,
      imgBaseUrlV0,
      imgBaseUrlV1,
      qrcodeURL: "",
      qrcodeSacnURL: "",
      imgList: [],
      userList: [],
      currentTab: 0,
      tabs: [
        {
          name: "设备档案",
        },
        {
          name: "服务申请记录",
        },
        {
          name: "维护记录",
        },
      ],
      equipment: null,

      /* 设备档案 */
      // 分类
      equipmentTypeSelectShow: false,
      equipmentTypeOptions: [],
      isEditEquipmentType: false,
      currentEquipmentTypeName: "",
      deleteTypeViewShow: false,
      showEquipmentTypeEdit: false,
      // 其他
      showContact: false,
      /* 服务申请记录 */
      serviceTypeOptions: [],
      serviceOrderRecords: [],

      /* 维护记录 */
      maintenanceRecords: [],
      isLoading: true,
      listQuery: {
        search: null,
        page: 1,
        limit: 20,
        sort: {
          id: "",
        },
        device_id: null,
      },
      mixinViewOptions: {
        getURL: "/device/detail",
        isPage: false,
        isShowLoading: false,
        reachBottom: false,
        createdIsNeed: false,
        pullDown: false,
      },
    };
  },
  async onLoad(e) {
    if (!e.equipmentId) return;
    if (e.name) {
      uni.setNavigationBarTitle({
        title: "设备数字档案 - " + e.name,
      });
    }

    this.listQuery.device_id = this.dataForm.id = e.equipmentId;
    this.init();

    this.$nextTick(async () => {
      this.openLoading();
      this.initData();
    });
  },
  async onPullDownRefresh() {
    uni.showLoading({
      title: "加载中",
    });
    await this.initData();
    uni.stopPullDownRefresh();
    uni.hideLoading();
  },
  async onReachBottom() {
    if (this.currentTab === 2) {
      this.listQuery.page++;
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
      await this.getMaintenanceRecords();
    }
  },
  methods: {
    fetchComplete(err, data = {}) {
      console.log(data, "??fetchComplete");
      data.user = (data.user || []).map((i) => {
        return {
          ...i,
          label: [i.name, i.mobile].join("/"),
          value: i.id,
        };
      });
      data.attachment = data.attachment || [];
      if (data.service_end_time) {
        data.service_end_time = this.$moment(data.service_end_time).format(
          "YYYY-MM-DD"
        );
      }
      if (data.company) {
        data.keyContact = [
          data.company.main_contact_name,
          data.company.contact_mobile,
        ].join("/");
      }
    },
    init() {
      this.qrcodeSacnURL = imgBaseUrlV2 + "qrcode.png";
      this.qrcodeURL = imgBaseUrlV1 + "exp_qrcode.jpg";
    },
    async initData() {
      let time = +new Date();
      await this.getDataInfo();
      await Promise.all([
        this.getEquipmentTypeOptions(),
        this.getCompanyUserList(),
        this.getServiceOrderRecords(),
        this.getMaintenanceRecords(),
      ])
        .then((res) => {})
        .catch((err) => {
          console.log("err", err);
        });
      let now = +new Date();

      if (now - time < 500) {
        await delayFunc(now - time);
      }
      this.isLoading = false;
      this.closeLoading();
    },
    onChangeTab(tab, index) {
      this.currentTab = index;
    },
    getCompanyUserList() {
      return getCompanyUserList({})
        .then((res) => {
          let data = res.data || [];
          data.forEach((i) => {
            i.checked = false;
            i.label = [i.name || "", i.mobile || ""].join("/");
            i.value = i.id;
          });
          this.userList = data;
          console.log(this.userList, "?? this.userList");
        })
        .catch((err) => {});
    },
    /* 设备数字档案 */
    getEquipmentTypeOptions() {
      return getEquipmentTypeOptions().then((response) => {
        this.equipmentTypeOptions = response;
      });
    },

    deleteEquipmentType(equipmentType) {
      if (this.isEditEquipmentType) {
        this.currentEquipmentTypeName = equipmentType;
        this.deleteTypeViewShow = true;
      }
    },

    getServiceOrderRecords() {
      return getServiceOrderRecords2({ device_id: this.dataForm.id }).then(
        (res) => {
          let data = res.data || {};
          let { list = [] } = data;
          let o = {
            2: "https://rhws.oss-cn-chengdu.aliyuncs.com/icon_v1/yiwancheng.png",
            3: "https://rhws.oss-cn-chengdu.aliyuncs.com/icon_v1/yiguanbi.png",
            0: "https://rhws.oss-cn-chengdu.aliyuncs.com/icon_v1/daigoutong.png",
            1: "https://rhws.oss-cn-chengdu.aliyuncs.com/icon_v1/jinxingzhong.png",
          };
          list.forEach((i) => {
            i.statusIcon = o[i.status] || o[0];

            i.title =
              (this.dataInfo.device_name || "") + "申请的" + i.service_content;
          });
          this.serviceOrderRecords = list;
        }
      );
    },
    openServiceRecordDetail(item, index) {
      Router.push({
        path: "/pages/service-order-detail/service-order-detail",
        query: {
          id: item.id,
          name: encodeURIComponent(item.device_name),
        },
      });
    },
    /* 维护记录 */
    getMaintenanceRecords() {
      return getMaintenanceRecords2(this.listQuery)
        .then((res) => {
          let page = this.listQuery.page || 1;
          let data = res.data || {};
          uni.hideLoading();
          const { list = [], total = 0 } = data;
          if (page <= 1) {
            this.maintenanceRecords.length = 0;
          }

          list.forEach((e) => {
            e.fold = true;
          });
          this.maintenanceRecords.push(...list);
          if (list.length == 0) {
            this.listQuery.page--;
            if (this.listQuery.page > 1) {
              return this.message.error("已无更多");
            }
          }
        })
        .catch(() => {
          uni.hideLoading();
        });
    },

    toggleFold(e) {
      e.fold = !e.fold;
      this.$forceUpdate();
    },
    openService() {
      uni.$emit("change-page", 1);
      console.log(
        this.dataInfo.servicer,
        "?this.dataInfo.service",
        this.dataInfo
      );
      Router.push({
        path: "/pages/service-provider-detail/service-provider-detail",
        query: {
          ...this.dataInfo.servicer,
        },
      });
    },
    onChangeSwiper(e) {
      let index = e.detail.current;
      this.currentTab = index;
    },
    onEdidUser() {
      this.userList.forEach((i) => {
        i.checked = (this.dataInfo.user || []).find((u) => u.id == i.id);
      });
      this.$refs.popup.open();
    },
    onUpload() {
      uni.chooseImage({
        count: 9,
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          let len = tempFilePaths.length;
          let load = 0;
          console.log(uploadUrl, "?uploadUrl", tempFilePaths);
          if (len) {
            uni.showLoading({
              title: "上传中",
            });
          }
          tempFilePaths.forEach((i) => {
            uni.uploadFile({
              url: uploadUrl, //仅为示例，非真实的接口地址
              filePath: i,
              name: "file",
              header: {
                authorization: "Bearer " + this.token,
              },
              formData: {
                // user: "test",
              },
              success: (uploadFileRes) => {
                let res = uploadFileRes.data;
                try {
                  res = JSON.parse(res);
                } catch (err) {
                  return this.message.error("上传图片失败,请重试");
                }
                let data = res.data;
                if (res.code !== this.$ERR_OK) {
                  return this.message.error(res.message || "上传图片失败");
                }
                let path = data.path;
                this.dataInfo.attachment.push(path);
                editAttachFile({
                  device_id: this.dataInfo.id,
                  img: this.dataInfo.attachment,
                });
              },
              complete: (r) => {
                load += 1;
                if (len == load) {
                  uni.hideLoading();
                }
              },
            });
          });
        },
      });
    },
    onDeleteImg(index) {
      let arr = this.dataInfo.attachment.slice(0);
      arr.splice(index, 1);
      uni.showLoading({
        title: "删除中",
      });
      editAttachFile({
        device_id: this.dataInfo.id,
        img: arr,
      })
        .then((res) => {
          uni.hideLoading();
          this.dataInfo.attachment.splice(index, 1);
        })
        .catch((err) => {
          uni.hideLoading();
        });
    },
    onCheckedUser(item, index) {
      item.checked = !item.checked;
      this.userList.splice(index, 1, item);
    },
    onConfirmUser() {
      let list = this.userList.filter((i) => i.checked);
      let ids = list.map((i) => i.id);
      uni.showLoading({
        title: "加载中",
      });
      editMaintrinUser({
        device_id: this.dataInfo.id,
        user_id: ids.join(","),
      })
        .then((res) => {
          uni.hideLoading();
          if (res.code !== this.$ERR_OK) {
            return this.message.error(res.message || "操作失败,请重试");
          }
          this.dataInfo.user = list.map((i) => {
            return {
              ...i,
              name: i.name,
            };
          });
        })
        .catch((err) => {
          uni.hideLoading();
        });
      this.close();
    },
    onCancelUser() {
      this.close();
    },
    closeLoading() {
      this.$refs.popupLoading && this.$refs.popupLoading.close();
    },
    openLoading() {
      this.$refs.popupLoading && this.$refs.popupLoading.open();
    },
    open() {
      this.$refs.popup && this.$refs.popup.open();
    },
    close() {
      this.$refs.popup && this.$refs.popup.close();
    },
    open() {
      this.$refs.popup && this.$refs.popup.open();
    },
    onClickShowQrcode() {
      Router.push({
        path: "/pageA/equipment/qrcode/index",
        query: {
          ...this.dataForm,
          equipmentId: this.dataInfo.thingId,
        },
      });
    },
    createQrcode(url) {
      console.log(url, "??");
    },
  },
};
</script>

<style lang="stylus" scoped>
@import '~@/common/stylus/variable';

.main, page {
  min-height: calc(100vh - var(--window-top));
  position: relative;
}

/* 设备数字档案 */
.equipment-infos {
  padding: 30rpx;
  box-sizing: border-box;

  .equipment-info {
    background-color: #fff;
    margin-bottom: 20rpx;
    border-radius: 8rpx;

    .title {
      position: relative;
      line-height: 80rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      color: #333;

      .operation {
        float: right;
        color: color-active;
        font-size: 28rpx;
      }

      &::after {
        content: '';
        position: absolute;
        left: 0;
        top: 20rpx;
        width: 2px;
        height: 40rpx;
        background-color: color-active;
      }
    }
  }

  .info {
    padding: 0 30rpx;
    font-size: 28rpx;
    color: #333;

    > .content {
      padding-bottom: 20rpx;
      display: flex;
      flex-direction: row;

      .text {
        flex: 1;

        .service-provider {
          border-bottom: 3rpx solid color-active;
          color: color-active;
        }
      }

      .qrcode {
        color: color-active;
      }

      .equipment-type-right-icon {
        width: 32rpx;
      }

      .equipment-type-view {
        display: inline;

        .equipment-type {
          display: inline;

          .equipment-type-text {
            &.delete-operation {
              border: 3rpx solid #f66;
              border-radius: 10rpx;
              padding: 0 5rpx;

              .delete {
                color: #f66;
                padding-left: 6rpx;
              }
            }
          }
        }
      }

      .contact-right-icon {
        width: 40rpx;
      }
    }
  }
}

.qrcode-view {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: rgba(0, 0, 0, 0.5);
  text-align: center;

  .qrcode {
    width: 450rpx;
    border-radius: 5rpx;
    margin-top: 250rpx;
  }

  .close-icon {
    width: 70rpx;
    height: 70rpx;
    margin-top: 50rpx;
  }
}

/* 服务申请记录 */
.service-records {
  position: relative;
  padding: 30rpx;

  >.item {
    margin-top: 20rpx;

    &:first-child {
      margin-top: 0;
    }
  }
}

/* 维护记录 */
.maintenance-view {
  padding: 30rpx;
}

.maintenance-record-group {
  background-color: #fff;
  padding: 25rpx 30rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;

  &:last-child {
    margin-bottom: 0;
  }

  .info {
    display: flex;

    >.bd {
      flex: 1;
      font-size: 30rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: color-describe;
    }

    .status-normal, .status-error {
      position: relative;
      display: flex;
      font-size: 24rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 600;
      padding: 0 12rpx;
      border-radius: 20rpx;
      line-height: 40rpx;
      align-items: center;
    }

    .circle {
      position: relative;
      width: 12rpx;
      height: 12rpx;
      border-radius: 12rpx;
      margin-right: 10rpx;
    }

    .status-normal {
      color: color-success;

      >.circle {
        background: color-success;
      }
    }

    .status-error {
      color: color-danger;

      >.circle {
        background: color-danger;
      }
    }
  }
}

.swiper {
  position: relative;
  height: calc(100vh - 82rpx - var(--window-top));
  overflow: auto;

  swiper-item {
    overflow: auto;
  }
}

.upload {
  padding: 0 20rpx;
}

.qrcodeURL {
  width: 30rpx;
  height: 30rpx;
  margin-left: 6rpx;
  margin-top: -4rpx;
  vertical-align: middle;
}
</style>